package com.example.myapplication.peripheral;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CSVDataLogger {
    private static final String DEFAULT_FILE_NAME = "default_log";
    private static final int DEFAULT_BATCH_SIZE = 1000;
    private String fileName;
    private int batchSize;
    private String dateFormat;
    private File csvFile;
    private BufferedWriter writer;
    private int cnt = 0;
    private StringBuilder stringBuilder = new StringBuilder();
    /**
     * 构造函数使用默认文件名和批量大小
     */
    public CSVDataLogger() {
        this(DEFAULT_FILE_NAME, DEFAULT_BATCH_SIZE,"");
    }
    /**
     * 构造函数
     * @param fileName 自定义文件名（不带扩展名）
     * @param batchSize 批量写入大小
     */
    public CSVDataLogger(String fileName, int batchSize,String str) {
        this.fileName = fileName;
        this.batchSize = batchSize;
        this.dateFormat = TimeUtils.getCurrentTime();
        // 初始化CSV文件
        initCSVFile(str);
    }

    /**
     * 初始化CSV文件，创建文件并写入标题行
     */
    private void initCSVFile(String str) {
        try {
            // 获取应用专属存储目录（适用于Android 10+）
            File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyAppData");
            if (!directory.exists()) {
                directory.mkdirs();
            }
            csvFile = new File(directory, fileName+ "_" + dateFormat + ".csv");
            // 如果文件不存在或为空，写入表头
            if (!csvFile.exists() || csvFile.length() == 0) {
                writer = new BufferedWriter(new FileWriter(csvFile, true));
                writer.write(str);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加浮点数组数据到缓冲区，当缓冲区满时自动写入文件
     * @param data 要存储的浮点数组数据
     */
    public void addData(float[] data) {
        // 获取当前时间戳
        String timestamp = TimeUtils.getMillisecond();
        // 添加到缓冲区
        synchronized (this) {
            for (int i = 0; i < data.length; i++) {
                stringBuilder.append(timestamp + "," + String.valueOf(data[i]) + "\n");
                cnt++;
            }
            // 检查是否达到批量大小
            if (cnt >= batchSize) {
                writeBatchToCSV();
            }
        }
    }
    public void addData(float[] data, float[] data1) {
        // 获取当前时间戳
        String timestamp = TimeUtils.getMillisecond();
        // 添加到缓冲区
        synchronized (this) {
            for (int i = 0; i < data.length; i++) {
                stringBuilder.append(timestamp + "," + String.valueOf(data[i]) +","+ String.valueOf(data1[i]) + "\n");
                Log.d("lzy","timestamp: "+timestamp);
                cnt++;
            }
            // 检查是否达到批量大小
            if (cnt >= batchSize) {
                writeBatchToCSV();
            }
        }
    }
    public void addData(float[] data, float[] data1, float[] data2) {
        // 获取当前时间戳
        String timestamp = TimeUtils.getMillisecond();
        // 添加到缓冲区
        synchronized (this) {
            for (int i = 0; i < data.length; i++) {
                stringBuilder.append(timestamp + "," + String.valueOf(data[i]) +","+ String.valueOf(data1[i]) +","+ String.valueOf(data2[i]) + "\n");
                cnt++;
            }
            // 检查是否达到批量大小
            if (cnt >= batchSize) {
                writeBatchToCSV();
            }
        }
    }
    public void addData(String[] data) {
        // 添加到缓冲区
        synchronized (this) {
            for (int i = 0; i < data.length; i++) {
                stringBuilder.append(data[i] + ",");
                cnt++;
            }
            stringBuilder.append("\n");
            // 检查是否达到批量大小
            if (cnt >= batchSize) {
                writeBatchToCSV();
            }
        }
    }
    public void addData(float[] data, float[] data1, float[] data2,float[] data3) {
        // 获取当前时间戳
        String timestamp = TimeUtils.getMillisecond();
        // 添加到缓冲区
        synchronized (this) {
            for (int i = 0; i < data.length; i++) {
                stringBuilder.append(timestamp + "," + String.valueOf(data[i]) +","+ String.valueOf(data1[i]) +","+ String.valueOf(data2[i]) +
                        ","+ String.valueOf(data3[i]) + "\n");
                cnt++;
            }
            // 检查是否达到批量大小
            if (cnt >= batchSize) {
                writeBatchToCSV();
            }
        }
    }

    /**
     * 将缓冲区中的数据写入CSV文件
     */
    public void writeBatchToCSV() {
        synchronized (this) {
            if (cnt == 0) {
                return;
            }
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter(csvFile, true));
                synchronized (this) {
                    writer.write(stringBuilder.toString());
                    stringBuilder.setLength(0);  // 清空内容
                    cnt = 0;
                }
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 强制将缓冲区中的数据写入文件（即使未达到批量大小）
     */
    public void flush() {
        writeBatchToCSV();
    }

    /**
     * 获取当前CSV文件的路径
     * @return CSV文件路径
     */
    public String getCSVFilePath() {
        return csvFile != null ? csvFile.getPath() : null;
    }
}